'use strict';

var React = require('react-native');

var {
	AppRegistry,
	StyleSheet,
	Text,
	View,
	Navigator,
	DrawerLayoutAndroid,
	BackAndroid,
	ToastAndroid
} = React;

var MainTabView = require('./app/MainTabView');
var LoginView = require('./app/LoginView');
var DrawerView = require('./app/DrawerView');
var ProductListView = require('./app/ProductListView');
var RefresherView = require('./test/RefresherView');

var initialRoute = {
	name: 'MainTabView',
	index: 0
}


var RN01 = React.createClass({

	componentDidMount: function() {

		let navigator = this.refs['navigator'];

		if (!navigator) return;

		let self = this;

		BackAndroid.addEventListener('hardwareBackPress', function() {

			var routes = navigator.getCurrentRoutes();
			//ToastAndroid.show('routes.length : ' + routes.length, ToastAndroid.SHORT);

			if (routes.length > 1) {
				navigator.pop();
				return true;
			}

			if (self._first_back_time && ((new Date() - self._first_back_time) < 2000)) {
				return false;
			} else {
				self._first_back_time = new Date();
				ToastAndroid.show('再按一次将退出', ToastAndroid.SHORT);
				return true;
			}
		});
	},

	render: function() {
		return (
			<DrawerLayoutAndroid
		      	drawerWidth={150}
				drawerPosition = {DrawerLayoutAndroid.positions.Left}
		      	renderNavigationView={() => <DrawerView/>}>
		      	<Navigator ref="navigator"
					initialRoute = {initialRoute}
					configureScene = {this.configureScene}
					renderScene = {this.renderScene}>
				</Navigator>
			</DrawerLayoutAndroid>
		);
	},

	configureScene: function(route) {
		if (route.sceneConfig) {
			return route.sceneConfig;
		}
		//return Navigator.SceneConfigs.FloatFromBottom;
		return Navigator.SceneConfigs.FloatFromRight;
	},

	renderScene: function(route, navigator) {

		function onForward() {
			var nextIndex = route.index + 1;
			navigator.push({
				name: route.name,
				index: nextIndex,
			});
		}

		function onBack() {
			if (route.index > 0) {
				navigator.pop();
			}
		}

		var SceneView = this.getSceneView(route);

		return (
			<SceneView name={route.name}
				navigator={navigator}
				onForward={onForward}
			    onBack={onBack}>
			</SceneView>
		)
	},

	getSceneView: function(route) {

		switch (route.name) {
			case 'MainTabView':
				return MainTabView;
			case 'LoginView':
				return LoginView;
			case 'ProductListView':
				return ProductListView;
			case 'RefresherView':
				return RefresherView;
		}
	},



});

var styles = StyleSheet.create({

});

AppRegistry.registerComponent('RN01', () => RN01);